package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSONObject;
import net.lcheng.model.*;
import net.lcheng.service.*;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.shop.vo.ProductUnityFormatModel;
import net.lcheng.shop.vo.ShopCategoryModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by LV on 2016/7/19.
 */
@Controller
public class ProductManageController {
    @Autowired
    private UserService userService;
    @Autowired
    private WxShopService shopService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WxShopCategoryService shopCategoryService;

    /**
     * 获取店铺的所有商品列表
     * @param model 模型
     * @return list
     */
    @RequestMapping(value = "/product/productManage",method = RequestMethod.GET)
    public String productManage(Model model){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop!=null) {
                        //获取该店铺的所有商品列表
                        List<PProduct> productList=productService.getProductListAll(shop.getShopId());
                        model.addAttribute("productList",productList);
                        return "/product_manage/publish_product_manage";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
            }
        return "redirect:/login";

    }

    /**
     * 根据状态查询所有商品
     * @param model 模型
     * @param status 商品状态
     * @return list
     */
    @RequestMapping(value = "/product/getProductByStatus",method = RequestMethod.GET)
    public String getProductByStatus(Model model,int status){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user!=null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop!=null) {
                        //获取该店铺的所有商品列表
                        List<PProduct> productList=productService.getProductListByStatus(shop.getShopId(),status);
                        model.addAttribute("productList",productList);
                        model.addAttribute("status",status);
                        return "product_manage/product_manage_status";
                    }
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 更改商品的状态
     * @param productId 要更改的商品的ID
     * @param status 需要改成的状态
     * @return String
     */
    @RequestMapping(value = "/product/changeProductStatus",method = RequestMethod.GET)
    public String changeProductStatus(@RequestParam("pid") String productId, @RequestParam("status") int status, HttpServletRequest request){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (productId!=null){
                int returnStatus=productService.updateProductStatus(productId,status);
                if (returnStatus>0) {
                    //从哪个页面来的就回哪个页面去
                   String url=request.getHeader("referer");
                    return "redirect:"+url;
                }else return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 选择分类（数据库分类列表添加一个判定该分类是否有子类，在分类列表里判断，如果没有子类，不让点击下一类）
     * @return String
     */
    @RequestMapping(value = "/product/selectClassify",method = RequestMethod.GET)
    public String selectClassify(Model model){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //一级分类列表
            List<PCategory> categoryList=categoryService.findCategoryListByParentCategoryId("");
            model.addAttribute("categoryList",categoryList);
            return "product_manage/product_category_select";
        }
        return "redirect:/login";
    }

    /**
     * 由父类Id查找子分类列表
     * @return list
     */
    @RequestMapping(value = "/product/selectClassifyByParentId",method = RequestMethod.GET)
    public String selectClassifyByParentId(Model model,@RequestParam("pcId") String parentCategoryId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //一级分类列表
            List<PCategory> categoryList=categoryService.findCategoryListByParentCategoryId(parentCategoryId);
            model.addAttribute("categoryList",categoryList);
            return "product_manage/product_category_select";
        }
        return "redirect:/login";
    }

    /**
     * 发布商品GET
     * @param model 模型
     * @param categoryId 商品分类主键
     * @return String
     */
    @RequestMapping(value = "/product/publishProduct",method = RequestMethod.GET)
    public String publishProduct(Model model,@RequestParam("cid") String categoryId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (categoryId!=null) {
                //获取分类的所有父类名字
                List<String> parentNames=categoryService.getParentCategoryName(categoryId);
                Collections.reverse(parentNames);

                model.addAttribute("parentNames",parentNames);
                model.addAttribute("categoryId",categoryId);
                return "/product_manage/product_publish";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存发布商品
     * @param unityFormatModel 表单模型
     * @param result 验证结果
     * @return String
     */
    @RequestMapping(value = "/product/savingPublishProduct",method = RequestMethod.POST)
    public String savingPublishProduct(Model model,@Valid @ModelAttribute("unityFormatModel") ProductUnityFormatModel unityFormatModel, BindingResult result){
        if (result.hasErrors()) {
            if (unityFormatModel!=null){
                //获取分类的所有父类名字
                List<String> parentNames=categoryService.getParentCategoryName(unityFormatModel.getCategoryId());
                Collections.reverse(parentNames);
                model.addAttribute("parentNames",parentNames);
                model.addAttribute("categoryId",unityFormatModel.getCategoryId());
                model.addAttribute("unityFormatModel", unityFormatModel);
                return "/product_manage/product_publish";
            }
            return "redirect:/error";
        }

        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        //将上传的图片的url拼接起来，用“|”分割
                        String imgs="";
                        if (unityFormatModel.getProductImgs()!=null&&unityFormatModel.getProductImgs().length>0){
                            String[] imgTmp=unityFormatModel.getProductImgs();
                            for (int $i=0;$i<imgTmp.length;$i++){
                                if (imgTmp[$i].equals("")&&imgTmp[$i]!=null) continue;
                                imgs+=(imgTmp[$i]+"|");
                            }
                            imgs=imgs.substring(0,imgs.lastIndexOf("|"));

                            //添加商品
                            PProduct product = new PProduct();
                            product.setProductId(UUID.randomUUID().toString());//商品主键
                            product.setpCategoryCategoryId(unityFormatModel.getCategoryId());//商品分类ID
                            product.setWxShopShopId(shop.getShopId());//店铺ID
                            product.setWxShopCategoryId("");//店铺分类ID在微信端，默认为空
                            product.setProductCode(unityFormatModel.getProductCode());//产品编码
                            product.setProductName(unityFormatModel.getProductName());//产品名称
                            product.setSalePrice(new BigDecimal(unityFormatModel.getSalePrice()));//产品销售价格
                            product.setFreight(new BigDecimal(unityFormatModel.getFreight()));//运费
                            product.setProductMainImage(unityFormatModel.getProductImgs()[0]);//商品主图片
                            product.setProductImages(imgs);//商品的所有图片
                            product.setStatus(1);//商品上架状态
                            product.setIsShopRecommend(1);//默认为店铺推荐
                            product.setCreateOn(new Date());//商品创建时间

                            int status=productService.addProduct(product);

                            if (status>0)
                                return "redirect:/product/productManage";
                            else
                                return "redirect:/error";
                        }
                        return "redirect:/error";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 店铺分类管理
     * @param model 模型
     * @return String
     */
    @RequestMapping(value = "/shop/manageShopCategory",method = RequestMethod.GET)
    public String manageShopCategory(Model model){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        //获取该店铺的所有分类
                        List<WxShopCategory> categoryList=shopCategoryService.getWxShopCategoryByShopId(shop.getShopId());
                        model.addAttribute("categoryList",categoryList);
                        return "/product_manage/shop_category_manage";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 编辑店铺分类
     * @param model 模型
     * @param shopCategoryId 分类主键
     * @return String
     */
    @RequestMapping(value = "/shop/editShopCategory",method = RequestMethod.GET)
    public String editShopCategory(Model model,@RequestParam("scId") String shopCategoryId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (shopCategoryId!=null){
                //获取分类信息
                WxShopCategory shopCategory=shopCategoryService.getWxShopCategoryByCategoryId(shopCategoryId);
                model.addAttribute("shopCategory",shopCategory);
                if (shopCategory!=null)
                    return "/product_manage/shop_category_edit";
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存修改的商品分类
     * @param result 验证结果对象
     * @return String
     */
    @RequestMapping(value = "/shop/savingEditShopCategory",method = RequestMethod.POST)
    public String savingEditShopCategory(Model model,@Valid @ModelAttribute("categoryModel") ShopCategoryModel categoryModel,BindingResult result){
        if (result.hasErrors()){
            model.addAttribute("shopCategory",categoryModel);
            return "/product_manage/shop_category_edit";
        }
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            WxShopCategory shopCategory=new WxShopCategory();
            shopCategory.setCategoryId(categoryModel.getCategoryId());
            shopCategory.setCategoryName(categoryModel.getCategoryName());
            shopCategory.setOrderNum(Integer.parseInt(categoryModel.getOrderNum()));
            shopCategory.setModifyOn(new Date());

            int status=shopCategoryService.modifyCategory(shopCategory);

            if (status>0)
                return "redirect:/shop/manageShopCategory";
            else
                return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 添加店铺分类GET
     * @return String
     */
    @RequestMapping(value = "/shop/addShopCategory",method = RequestMethod.GET)
    public String addShopCategory() {
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {

            return "/product_manage/shop_category_add";
        }

        return "redirect:/login";
    }


    /**
     * 保存添加的分类
     * @param model 模型
     * @param result 验证结果
     * @return String
     */
    @RequestMapping(value = "/shop/savingAddShopCategory",method = RequestMethod.POST)
    public String savingAddShopCategory(Model model,@Valid @ModelAttribute("categoryModel") ShopCategoryModel categoryModel,BindingResult result){
        if (result.hasErrors()){
            model.addAttribute("categoryModel",categoryModel);
            return "/product_manage/shop_category_add";
        }
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        WxShopCategory shopCategory=new WxShopCategory();
                        shopCategory.setCategoryId(UUID.randomUUID().toString());//主键
                        shopCategory.setCategoryName(categoryModel.getCategoryName());//分类名
                        shopCategory.setOrderNum(Integer.parseInt(categoryModel.getOrderNum()));
                        shopCategory.setShopId(shop.getShopId());
                        shopCategory.setStatus(1);
                        shopCategory.setCreateOn(new Date());
                        int status=shopCategoryService.addCategory(shopCategory);
                        if (status>0)
                            return "redirect:/shop/manageShopCategory";
                        else
                            return "redirect:/error";
                    }
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 删除店铺分类
     * @param shopCategoryId 要删除店铺分类Id
     * @return String
     */
    @RequestMapping(value = "/shop/deleteShopCategory",method = RequestMethod.GET)
    public String deleteShopCategory(@RequestParam("scId") String shopCategoryId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (shopCategoryId!=null&&!shopCategoryId.equals("")){
                //删除店铺分类
                int status=shopCategoryService.deleteShopCategoryByPrimaryKey(shopCategoryId);
                if (status>0)
                    return "redirect:/shop/manageShopCategory";
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 产品移动分类
     * @param model 模型
     * @param productId 要移动分类的产品Id
     * @return String
     */
    @RequestMapping(value = "/product/productMoveShopCategory",method = RequestMethod.GET)
    public String productMoveShopCategory(Model model,@RequestParam("pid") String productId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (productId!=null&&!productId.equals("")){
                //获取产品信息
                PProduct product=productService.getProductByPrimaryKey(productId);
                if (product!=null){
                    //获取该产品所属店铺的所有分类
                    List<WxShopCategory> shopCategories=shopCategoryService.getWxShopCategoryByShopId(product.getWxShopShopId());
                    model.addAttribute("shopCategories",shopCategories);
                    model.addAttribute("productId",productId);
                    return "/product_manage/product_move_shop_category";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 产品移动分类（店铺的产品改变分类）
     * @param productId 需要改变分类的产品Id
     * @param categoryId 要改成的分类
     * @return String
     */
    @RequestMapping(value = "/product/changeProductShopCategory",method = RequestMethod.GET)
    public String changeProductShopCategory(@RequestParam("pid") String productId,@RequestParam("cid") String categoryId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (productId!=null&&!productId.equals("")&&categoryId!=null&&!categoryId.equals("")){
                int status=productService.changeProductShopCategory(productId,categoryId);
                if (status>0)
                    return "redirect:/product/productManage";//重定向到产品管理页
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }
}
